/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package canteen.sys.view;

import canteen.sys.model.entity.Store;
import canteen.sys.model.generic.HibernateDAOFactory;
import java.util.Calendar;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import org.hibernate.HibernateException;

/**
 *
 * @author TNT
 */
public class StoreM extends javax.swing.JInternalFrame implements ActionView<Store> {
    
    HibernateDAOFactory hibernateDAOFactory = HibernateDAOFactory.getInstance();
    DefaultTableModel modelTableStore;
    List<Store> listStore;

    /**
     * Creates new form StoreM
     */
    public StoreM() {
        initComponents();
        modelTableStore = (DefaultTableModel) tbstore.getModel();
        if (listStore == null) {
            listStore = hibernateDAOFactory.getStoreDAO().findAllByStatus(true);
            showList(listStore);
        } else {
            showList(null);
        }
        listenerTableModel();
        listSelectionListener();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        txtdescription = new javax.swing.JTextArea();
        txtname = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        rbstatus = new javax.swing.JRadioButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        tbstore = new javax.swing.JTable();
        jLabel4 = new javax.swing.JLabel();
        txtaddress = new javax.swing.JTextField();
        btaddnew = new javax.swing.JButton();
        btrefresh = new javax.swing.JButton();
        btdelete = new javax.swing.JButton();
        cbstatus = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();

        setClosable(true);
        setTitle("Kho lưu trữ");

        txtdescription.setColumns(20);
        txtdescription.setRows(5);
        jScrollPane1.setViewportView(txtdescription);

        jLabel1.setText("Tên kho: ");

        jLabel2.setText("Mô tả: ");

        jLabel3.setText("Trạng thái");

        rbstatus.setSelected(true);

        tbstore.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Tên Kho", "Trạng thái"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(tbstore);
        tbstore.getColumnModel().getColumn(1).setMinWidth(100);
        tbstore.getColumnModel().getColumn(1).setMaxWidth(100);

        jLabel4.setText("Địa chỉ:");

        btaddnew.setText("Thêm mới");
        btaddnew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btaddnewActionPerformed(evt);
            }
        });

        btrefresh.setText("Làm mới");
        btrefresh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btrefreshActionPerformed(evt);
            }
        });

        btdelete.setText("Xóa");
        btdelete.setEnabled(false);
        btdelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btdeleteActionPerformed(evt);
            }
        });

        cbstatus.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Hiện", "Ẩn" }));
        cbstatus.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbstatusActionPerformed(evt);
            }
        });

        jLabel5.setText("Trạng Thái");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbstatus, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btaddnew, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btrefresh, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btdelete, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(txtaddress, javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(txtname, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE))
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 295, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel3)
                                        .addGap(18, 18, 18)
                                        .addComponent(rbstatus)))
                                .addGap(15, 15, 15)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 317, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cbstatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel4)
                        .addGap(2, 2, 2)
                        .addComponent(txtaddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 267, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(rbstatus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btaddnew)
                            .addComponent(btrefresh)
                            .addComponent(btdelete)))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 440, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btaddnewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btaddnewActionPerformed
        // TODO add your handling code here:
        try {
            Store store = new Store();
            if (btaddnew.getText().equals("Thêm mới")) {
                store.setName(txtname.getText());
                store.setDescription(txtdescription.getText());
                store.setAddress(txtaddress.getText());
                store.setModifiedDate(new java.sql.Date(Calendar
                        .getInstance().getTimeInMillis()));
                store.setStatus(rbstatus.isSelected());
                validInsertStore(store);
            } else {
                int selectedIndex = tbstore.getSelectedRow();
                if (selectedIndex != -1) {
                    store = listStore.get(listStore
                            .size() - 1 - selectedIndex);
                    store.setName(txtname.getText());
                    store.setAddress(txtaddress.getText());
                    store.setDescription(txtdescription.getText());
                    store.setStatus(rbstatus.isSelected());
                    store.setModifiedDate(new java.sql.Date(Calendar
                            .getInstance().getTimeInMillis()));
                    validInsertStore(store);
                    btaddnew.setText("Thêm mới");
                    btrefresh.setText("Làm mới");
                }
            }
            this.txtname.requestFocus();
        } catch (HibernateException ex) {
            JOptionPane.showMessageDialog(this,
                    "Thêm mới Tên Kho lỗi!\n Lỗi: " + ex.getMessage(),
                    "Lỗi", JOptionPane.ERROR_MESSAGE);
        }
        txtname.selectAll();
        rbstatus.setSelected(true);
    }//GEN-LAST:event_btaddnewActionPerformed
    
    private void btrefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btrefreshActionPerformed
        // TODO add your handling code here:
        if (btrefresh.getText().equals("Làm mới")) {
            txtname.setText("");
            txtdescription.setText("");
            rbstatus.setSelected(true);
        } else {
            clearAll();
        }
    }//GEN-LAST:event_btrefreshActionPerformed
    
    private void btdeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btdeleteActionPerformed
        // TODO add your handling code here:
        if (JOptionPane.showConfirmDialog(this, "Bạn có chắc chắn?", "Cảnh báo",
                JOptionPane.WARNING_MESSAGE) == JOptionPane.OK_OPTION) {
            try {
                if (tbstore.getSelectedRow() != -1) {
                    deleteRow(tbstore.getSelectedRow());
                    Store store = listStore.get(listStore.size() - 1 - tbstore.getSelectedRow());
                    hibernateDAOFactory.getStoreDAO().makeTransient(store);
                    btaddnew.setText("Thêm mới");
                    btrefresh.setText("Làm mới");
                    btdelete.setEnabled(false);
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "Không thể xóa được, "
                        + "Kho này đã được sử dụng!\n");
            }
        }
    }//GEN-LAST:event_btdeleteActionPerformed
    
    private void cbstatusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbstatusActionPerformed
        // TODO add your handling code here:
        clearAll();
        listStore.clear();
        boolean status = false;
        if (cbstatus.getSelectedIndex() == 0) {
            status = true;
        }
        listStore = hibernateDAOFactory.getStoreDAO().findAllByStatus(status);
        showList(listStore);
    }//GEN-LAST:event_cbstatusActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btaddnew;
    private javax.swing.JButton btdelete;
    private javax.swing.JButton btrefresh;
    private javax.swing.JComboBox cbstatus;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JRadioButton rbstatus;
    private javax.swing.JTable tbstore;
    private javax.swing.JTextField txtaddress;
    private javax.swing.JTextArea txtdescription;
    private javax.swing.JTextField txtname;
    // End of variables declaration//GEN-END:variables
    @Override
    public void deleteRow(int index) {
        if (modelTableStore.getRowCount() > 0) {
            if (index > 0) {
                tbstore.setRowSelectionInterval(index - 1, index - 1);
                modelTableStore.removeRow(index);
            } else {
                tbstore.setRowSelectionInterval(index + 1, index + 1);
                modelTableStore.removeRow(0);
            }
        } else {
            JOptionPane.showMessageDialog(this, "Không có dòng nào để xóa!",
                    "Cảnh báo!", JOptionPane.WARNING_MESSAGE);
        }
    }
    
    @Override
    public void updateRow(Store row, int index) {
        modelTableStore.setValueAt(row.getName(), index, 0);
        if (row.isStatus()) {
            modelTableStore.setValueAt("Hiện", index, 1);
        } else {
            modelTableStore.setValueAt("Ẩn", index, 1);
        }
    }
    
    @Override
    public void addRow(Store row, boolean posion) {
        String status = "Hiện";
        if (!row.isStatus()) {
            status = "Ẩn";
        }
        if (posion) {
            modelTableStore.insertRow(0, new Object[]{row.getName() + "",
                        status});
        } else {
            modelTableStore.insertRow(tbstore.getRowCount(),
                    new Object[]{row.getName() + "", status});
        }
        listStore.add(row);
    }
    
    @Override
    public final void showList(List<Store> list) {
        String status;
        int totalrow = tbstore.getRowCount();
        if (totalrow > 0) {
            for (int i = 0; i < totalrow; i++) {
                modelTableStore.removeRow(0);
            }
        }
        if (list != null && list.size() > 0) {
            for (Store item : list) {
                if (item.isStatus()) {
                    status = "Hiện";
                } else {
                    status = "Ẩn";
                }
                modelTableStore.insertRow(0, new Object[]{item.getName()
                            + "", status});
            }
        }
    }
    
    @Override
    public void showDetail(Store object) {
        txtname.setText(object.getName());
        txtdescription.setText(object.getDescription());
        txtaddress.setText(object.getAddress());
        rbstatus.setSelected(object.isStatus());
    }
    
    @Override
    public Store getObject(int index) {
        Store author = new Store();
        try {
            if (listStore != null && listStore.size() > 0 && cbstatus.isFocusOwner() == false) {
                int indexOfList = listStore.size() - 1 - index;
                author = listStore.get(indexOfList);
            }
        } catch (ArrayIndexOutOfBoundsException ex) {
        }
        return author;
    }
    
    @Override
    public void setObject(Store object) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
    @Override
    public boolean validObject(Store object) {
        if (object.getName().equals("") || object.getName() == null) {
            JOptionPane.showMessageDialog(this, "Tên Kho lưu chữ chưa được nhập!");
            return false;
        } else if (object.getAddress().equals("") || object.getAddress() == null) {
            JOptionPane.showMessageDialog(this, "Địa chỉ Kho lưu chữ chưa được nhập!");
            return false;
        }
        return true;
    }
    
    public final void listSelectionListener() {
        tbstore.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                int rowSelected = tbstore.getSelectedRow();
                showDetail(getObject(rowSelected));
                btaddnew.setText("Sửa");
                btrefresh.setText("Hủy");
                btdelete.setEnabled(true);
            }
        });
    }
    
    public final void listenerTableModel() {
        modelTableStore.addTableModelListener(new TableModelListener() {
            @Override
            public void tableChanged(TableModelEvent e) {
                if (e.getType() == TableModelEvent.DELETE && cbstatus.isFocusOwner() == false) {
                    JOptionPane.showMessageDialog(null, "Xóa thành công!");
                } else if (e.getType() == TableModelEvent.INSERT && cbstatus.isFocusOwner() == false) {
                    JOptionPane.showMessageDialog(null, "Thêm Tên Kho thành công!");
                } else if (e.getType() == TableModelEvent.UPDATE && e.getColumn() == 1 && cbstatus.isFocusOwner() == false) {
                    JOptionPane.showMessageDialog(null, "Sửa Tên Kho thành công!");
                }
            }
        });
    }
    
    private void validInsertStore(Store store) {
        if (validObject(store)) {
            Store storeResult = hibernateDAOFactory.getStoreDAO().makePersistent(store);
            showDetail(storeResult);
            if (btaddnew.getText().equals("Thêm mới")) {
                addRow(store, true);
            } else {
                updateRow(store, tbstore.getSelectedRow());
            }
        }
    }
    
    private void clearAll() {
        txtname.setText("");
        txtdescription.setText("");
        rbstatus.setSelected(true);
        btaddnew.setText("Thêm mới");
        btrefresh.setText("Làm mới");
        btdelete.setEnabled(false);
    }
}
